<template>
  <div>
    <div
      style="font-weight:bold;padding:2px;text-shadow:0 0 1px #fff, 0 1px 2px rgba(0, 0, 0, 0.3);margin-bottom:6px;text-align:center;background:linear-gradient(30deg, #e62525 0%, #dadc5fdb 50%, #f9fafc 100%)"
    >{{ stockName }}
    </div>
    <div style="text-align:center">
      <el-button type="danger" :class="{typeClass:typeIndex===1}" icon="el-icon-s-data" size="mini" @click="switchType('day')">日</el-button>
      <el-button type="danger" :class="{typeClass:typeIndex===2}" icon="el-icon-s-data" size="mini" @click="switchType('week')">周</el-button>
      <el-button type="danger" :class="{typeClass:typeIndex===3}" icon="el-icon-s-data" size="mini" @click="switchType('month')">月</el-button>
      <el-button type="danger" :class="{typeClass:typeIndex===4}" icon="el-icon-s-data" size="mini" @click="switchType('quarter')">季</el-button>
      <el-button type="danger" :class="{typeClass:typeIndex===5}" icon="el-icon-s-data" size="mini" @click="switchType('year')">年</el-button>
    </div>
    <div :id="chartDivId" style="width:100%;height:1200px"></div>
  </div>
</template>

<script>
import kLineStyle from './kLineStyle'
import dayjs from 'dayjs'
import weekday from 'dayjs/plugin/weekday'
import quarterOfYear from 'dayjs/plugin/quarterOfYear'
import 'dayjs/locale/zh-cn'

dayjs.extend(weekday)
dayjs.extend(quarterOfYear)
dayjs.locale('zh-cn')
import { init } from 'klinecharts'
import { getHistoryPriceByStockCode } from '@/api/eye/stockPrice'

export default {
  name: 'ShowKLineCharts',
  data() {
    return {
      chart: null,
      typeIndex: 0,
      dayDate: [],
      dayPrice: [],
      dayKLineData: []
    }
  },
  // 父组件向子组件传递的参数
  props: {
    chartDivId: {
      type: String,
      default: 'defaultDivId'
    },
    stockCode: {
      type: String,
      default: ''
    },
    stockName: {
      type: String,
      default: ''
    },
    /* 高度 */
    height: {
      type: Number,
      default: null
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null
    }
  },

  created() {
    console.log('created')
  },

  mounted() {
    console.log('mounted')
    let chartDivId = this.chartDivId

    // 初始化图表
    this.chart = init(`${chartDivId}`)
    getHistoryPriceByStockCode(this.stockCode).then(res => {
      this.dayDate = res.data.date
      this.dayPrice = res.data.price

      let kLineData = []
      for (let i = 0; i < this.dayDate.length; i++) {
        let item = {}
        item.open = this.dayPrice[i][0]
        item.close = this.dayPrice[i][1]
        item.low = this.dayPrice[i][2]
        item.high = this.dayPrice[i][3]
        item.volume = this.dayPrice[i][4]
        item.timestamp = new Date(this.dayDate[i]).getTime()
        kLineData.push(item)
      }
      this.dayKLineData = kLineData
      this.chart.createIndicator('MA', false, { id: 'candle_pane' })
      this.chart.overrideIndicator({ name: 'MA', calcParams: [5, 10, 20, 30, 60, 125, 250] })
      this.chart.createIndicator('VOL', false, { height: 100, dragEnabled: false })
      this.chart.createIndicator('KDJ', false, { height: 100, dragEnabled: false })
      this.chart.createIndicator('MACD', false, { height: 100, dragEnabled: false })
      this.chart.createIndicator('BOLL', false, { height: 100, dragEnabled: false })
      this.chart.createIndicator('SAR', false, { height: 100, dragEnabled: false })
      this.chart.createIndicator('BBI', false, { height: 100, dragEnabled: false })
      this.chart.createIndicator('DMI', false, { height: 100, dragEnabled: false })
      this.chart.createIndicator('RSI', false, { height: 100, dragEnabled: false })
      this.chart.setStyles(kLineStyle())
      this.chart.applyNewData(kLineData)
    })
  },
  methods: {
    switchType(type) {
      let choose = {day:1,week:2,month:3,quarter:4,year:5}
      this.typeIndex = choose[type]
      let d = this.dayDate
      let price = this.dayKLineData
      let length = d.length
      let date = new Date(d[0])
      //周、月、季度、年的第一天
      let firstDay = dayjs(date).startOf(type)
      //周、月、季度、年的最后一天
      let lastDay = dayjs(date).endOf(type)

      let kLine = []
      let tmp = []
      // 转周K、月K、季度K、年K
      for (let n = 0; n < length; n++) {
        if (new Date(d[n]) >= firstDay && new Date(d[n]) <= lastDay) {
          tmp.push(price[n])
        } else {
          if (tmp.length > 0) {
            kLine.push({
              timestamp: tmp[tmp.length - 1].timestamp,
              // 开盘价是范围内的第一天的开盘价
              open: tmp[0].open,
              // 收盘价是范围内的最后一天的收盘价
              close: tmp[tmp.length - 1].close,
              // 最高价是范围内的最低价
              low: Math.min.apply(Math, tmp.map(item => {
                return item.low
              })),
              // 最高价是范围内的最高价
              high: Math.max.apply(Math, tmp.map(item => {
                return item.high
              })),
              // 成交量是范围内的总和
              volume: tmp.map(item => item.volume).reduce((prev, curr) => prev + curr, 0)
            })
            date = new Date(d[n])
            //周、月、季度、年的第一天
            firstDay = dayjs(date).startOf(type)
            //周、月、季度、年的最后一天
            lastDay = dayjs(date).endOf(type)
          }
          tmp = []
          tmp.push(price[n])
        }
      }

      // 添加最后的数据
      if (tmp.length > 0) {
        kLine.push({
          timestamp: tmp[tmp.length - 1].timestamp, open: tmp[0].open,
          close: tmp[tmp.length - 1].close,
          low: Math.min.apply(Math, tmp.map(item => {
            return item.low
          })),
          high: Math.max.apply(Math, tmp.map(item => {
            return item.high
          })),
          volume: tmp.map(item => item.volume).reduce((prev, curr) => prev + curr, 0)
        })
      }
      this.chart.applyNewData(kLine)
    }
  }
}
</script>

<style scoped>
.typeClass{
  background-color: #1890ff;
}
</style>
